extern int yylineno;

#include "TreeNode.h"

TreeNode* createNode(char* name,char* val){
  TreeNode* p=(TreeNode*)malloc(sizeof(TreeNode));
  strcpy(p->name,name);
  strcpy(p->attr_val,val);
  p->row=yylineno;
  p->sib=NULL;
  p->des=NULL;
  return p;
}

void insertDescendent(TreeNode* p,TreeNode* des){
  assert(p);
  if(des==NULL)
    return; //syntax.y can definitely insert a NULL child to p
  else{
    des->sib=p->des;
    p->des=des;
    p->row=des->row;
  }
}

void drawTree(TreeNode* r,int intent){
  if(r){
    for(int i=0;i<intent;i++)
      printf("  ");
    if(r->des){
    	printf("%s (%d)\n",r->name,r->row);
    	TreeNode* p=r->des;
    	while(p){
    	  drawTree(p,intent+1);
    	  p=p->sib;
	    }
    }
    else{
    	if(strcmp(r->name,"FLOAT")==0)
    	  printf("FLOAT: %f\n",atof(r->attr_val));
    	else if(strcmp(r->name,"INT")==0)
    	  printf("INT: %d\n",interpret(r->attr_val));
    	else if(strcmp(r->name,"ID")==0||strcmp(r->name,"TYPE")==0)
    	  printf("%s: %s\n",r->name,r->attr_val);
    	else
    	  printf("%s\n",r->name);
    }
  }
}

int interpret(char * str){//之前根本不知道有strtol函数 string to long 可以任意进制
  assert(str);

  int result;

  if(str[0]=='0'){
    if(str[1]=='\0')
      result=0;
    else if(str[1]=='x' || str[1]=='X')
      sscanf(str+2,"%x",&result);
    else 
      sscanf(str+1,"%o",&result);
  }
  else
    sscanf(str,"%d",&result);
  
  return result;
}
